﻿namespace Leetcode.N0056;
public class Solution
{

    public int[][] Merge(int[][] intervals)
    {
        var ans = new List<int[]>();
        intervals = intervals.OrderBy(_ => _[0]).ToArray();

        var interval = intervals[0];

        for (int i = 1; i < intervals.Length; i++)
        {
            if (intervals[i][0] > interval[1] || intervals[i][1] < interval[0])
            {
                ans.Add(interval);
                interval = intervals[i];
            }
            else
            {
                interval[0] = Math.Min(interval[0], intervals[i][0]);
                interval[1] = Math.Max(interval[1], intervals[i][1]);
            }
        }

        ans.Add(interval);
        return ans.ToArray();
    }
}